<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 考勤查询 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>

                <el-select v-model="query.status" placeholder="状态" class="handle-select mr10">
                    <el-option key="1" label="状态" value=""></el-option>
                    <el-option key="2" label="签到" value="01"></el-option>
                    <el-option key="3" label="未签到" value="00"></el-option>
                </el-select>

                <el-select v-model="query.result" placeholder="结果" class="handle-select mr10">
                    <el-option key="1" label="结果" value=""></el-option>
                    <el-option :key="index" v-for="(item, index) in result" :value="index" :label="item"></el-option>
                </el-select>

                <el-date-picker
                    v-model="query.date"
                    type="date"
                    :format="dateformat"
                    :value-format="dateformat"
                    placeholder="选择日期"
                    class="mr"
                >
                </el-date-picker>

                <el-input v-model="query.name" placeholder="员工姓名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="warning" icon="el-icon-plus" @click="addCheck">添加考勤</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="tid" label="员工编号"></el-table-column>
                <el-table-column prop="name" label="员工姓名"></el-table-column>
                <el-table-column prop="date" label="打卡日期" ></el-table-column>
                <el-table-column prop="startTime" label="签到时间" :formatter="formatTime"></el-table-column>
                <el-table-column prop="endTime" label="签退时间" :formatter="formatTime"></el-table-column>
                <el-table-column prop="status" label="签到状态" :formatter="formatStatus"></el-table-column>
                <el-table-column prop="result" label="签到结果" :formatter="formatResult"></el-table-column>
                <el-table-column label="操作" align="center" width="350px">
                    <template slot-scope="scope">
                        <el-button type="success" size="mini" icon="el-icon-view" @click="view(scope.row.id)">详情</el-button>
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scope.row.id)">编辑</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-close" @click="del(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-row justify="space-between">
                <el-col :span="8" :offset="8">
                    <el-button type="success" class="export" icon="el-icon-document" @click="exportChecks">导出execl</el-button>
                </el-col>
                <el-col :span="8">
                    <div class="pagination">
                        <el-pagination
                            background
                            layout="total, prev, pager, next"
                            :current-page="query.pageNum"
                            :page-size="query.pageSize"
                            :total="pageTotal"
                            @current-change="handlePageChange"
                        ></el-pagination>
                    </div>
                </el-col>
            </el-row>

            <!-- 添加考勤表单 -->
            <el-dialog title="添加考勤" :visible.sync="dialogFormVisible" width="350px">
                <el-form :model="form" ref="form" :rules="rules">
                    <el-form-item label="部门" prop="did">
                        <el-select v-model="form.did" placeholder="请选择部门">
                            <el-option :label="item.name" v-for="(item, index) in depts" :key="index" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="日期" prop="date">
                        <el-date-picker
                            v-model="form.date"
                            type="date"
                            :format="dateformat"
                            :value-format="dateformat"
                            :picker-options="pickerOptions"
                            placeholder="选择日期"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeAddCheck">取 消</el-button>
                    <el-button type="primary" @click="SureAddCheck('form')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
export default {
    name: 'basetable',
    inject: ['reload'],
    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now();
                }
            },
            query: {
                tid: '',
                status: '',
                date: '',
                result: '',
                name: '',
                pageNum: 1,
                pageSize: 5
            },
            export: {
                tid: '',
                status: '',
                date: '',
                result: '',
                name: ''
            },
            form: {
                did: '',
                date: ''
            },
            rules: {
                did: [{ required: true, trigger: 'blur' }],
                date: [{ required: true, trigger: 'blur' }]
            },
            depts: [],
            dialogFormVisible: false,
            dateformat: 'yyyy-MM-dd',
            result: {},
            employees: [],
            tableData: [],
            multipleSelection: [],
            delList: [],
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getDepts();
        this.getResult();
        this.init();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        async init() {
            var d = await this.$http.post('/checks', this.query);
            if (d.code == 200) {
                if (d.data != null) {
                    this.tableData = d.data.list;
                    this.pageTotal = d.data.total;
                } else {
                    this.tableData = [];
                }
            } else {
                this.$message.error(d.message);
            }
        },
        async getDepts() {
            var condition = {
                status: '01'
            };
            var d = await this.$http.post('/deptMap', condition);
            if (d.code == 200) {
                this.depts = d.data;
            }
        },
        async exportChecks() {
           await this.$http.post("/exportChecks", this.query, { responseType: 'arraybuffer' }).then((_res) => {
                    const blob = new Blob([_res], { type: 'application/vnd.ms-excel;' })
                    const a = document.createElement('a')
                    // 生成文件路径
                    let href = window.URL.createObjectURL(blob)
                    a.href = href
                    // 文件名中有中文 则对文件名进行转码
                    a.download = decodeURIComponent("check.xls")
                    // 利用a标签做下载
                    document.body.appendChild(a)
                    a.click()
                    document.body.removeChild(a)
                    window.URL.revokeObjectURL(href)
                })
        },
        //获取结果数据
        getResult() {
            this.result = JSON.parse(window.sessionStorage.getItem('result'));
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.init();
            this.export = this.query;
        },
        // 编辑操作
        view(id) {
            this.$router.push({ path: '/getCheck', query: { id: id } });
        },
        // 编辑操作
        edit(id) {
            this.$router.push({ path: '/updateCheck', query: { id: id } });
        },
        // 删除操作
        del(id) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(async () => {
                    var d = await this.$http.delete('/check/' + id);
                    if (d.code == 200) {
                        this.$message.success(d.message);
                        this.reload();
                    } else {
                        this.$message.error(d.message);
                    }
                })
                .catch(() => {});
        },
        //格式化表格
        formatTime(row, column, cellValue, index) {
            if (cellValue) {
               return cellValue;
            } else {
                return '暂未签到';
            }
        },
        
        formatStatus(row, column, cellValue, index) {
            return cellValue === '01' ? '已签到' : '未签到';
        },

        formatResult(row, column, cellValue, index) {
            switch (cellValue) {
                case '00':
                    return '迟到';
                case '01':
                    return '正常';
                case '02':
                    return '早退';
                case '03':
                    return '缺席';
                case '04':
                    return '请假';
                case '05':
                    return '未签退';
                case '06':
                    return '迟到且早退';
                default:
                    return '暂未签到';
            }
        },

        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //批量删除
        async delAllSelection() {
            const length = this.multipleSelection.length;
            var delName = '';
            for (let i = 0; i < length; i++) {
                this.delList.push(this.multipleSelection[i].id);
                delName = delName + this.multipleSelection[i].name + ' ';
            }
            this.$confirm('确定要删除 ' + delName + '吗？', '提示', {
                type: 'warning'
            })
                .then(async () => {
                    var d = await this.$http.post('/delChecks', this.delList);
                    if (d.code == 200) {
                        this.$message.success(d.message);
                        this.multipleSelection = [];
                        this.reload();
                    } else {
                        this.$message.error(d.message);
                    }
                })
                .catch(() => {});
        },
        // 分页导航
        handlePageChange(val) {
            this.query.pageNum = val;
            this.init();
        },
        //添加考勤
        addCheck() {
            this.dialogFormVisible = true;
        },
        closeAddCheck() {
            this.form.did = '';
            this.form.date = '';
            this.dialogFormVisible = false;
        },
        SureAddCheck(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    var d = await this.$http.post('/addCheck', this.form);
                    this.$message.success(d.message);
                    this.reload();
                } else {
                    this.$message.error(d.message);
                }
            });
            this.dialogFormVisible = false;
        }
    }
};
</script>

<style scoped>
.export {
    margin: 20px 0 0 100px;
}
.mr {
    margin-right: 10px;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
